'use client'
import React, { use, useEffect, useState } from 'react'
import { Space, Table, Modal, Tag, Button, Tabs, Input, Select, DatePicker, Popconfirm,message } from 'antd';
import { getLyh,deleteLyh } from '@/app/axios/http';
import {
  WechatOutlined,
  SignatureOutlined,
  VerticalAlignTopOutlined,
  DeleteOutlined,
  PlusOutlined,
  VerticalAlignBottomOutlined,
  RetweetOutlined, ImportOutlined,
  SearchOutlined,
  UndoOutlined,
  FunnelPlotOutlined
} from '@ant-design/icons';
import Myform from './myForm';
export default function page() {
  const [list, setList] = useState([])
  // 定义一个状态变量pagination，用于存储分页信息
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 5,
    total: 0,
  })
  // 定义一个状态变量name，用于存储模态框标题
  const [name, setName] = useState('')
  // 定义一个状态变量isModalOpen，用于控制模态框的显示与隐藏
  const [isModalOpen, setIsModalOpen] = useState(false);

  // 定义一个函数showModal，用于打开模态框
  const showModal = () => {
    setIsModalOpen(true);
  };

  // 定义一个函数handleOk，用于关闭模态框
  const handleOk = () => {
    setIsModalOpen(false);
  };

  // 定义一个函数handleCancel，用于关闭模态框
  const handleCancel = () => {
    setIsModalOpen(false);
  };
  // 定义一个状态变量data，用于存储获取到的数据
  let [data, setData] = useState([])

  // 处理表格变化
  const handleTableChange = (pagination: any) => {
    // 设置分页
    setPagination(pagination)
  }
  // 使用useEffect钩子函数，在组件加载时获取数据
  function mm() {
    getLyh().then((res) => {
      setData(res) // Extract the data property from AxiosResponse
      setPagination({
        ...pagination,
        total: res.length,
      })
    })

  }
  // 在组件状态中添加置顶数据的ID数组
  const [pinnedIds, setPinnedIds] = useState<string[]>([]);

  // 修改表格数据源，将置顶数据放在前面
  const sortedData = [...data].sort((a, b) => {
    const aIsPinned = pinnedIds.includes(a.id);
    const bIsPinned = pinnedIds.includes(b.id);

    if (aIsPinned && !bIsPinned) return -1;
    if (!aIsPinned && bIsPinned) return 1;
    return 0;
  });
  useEffect(() => {
    mm()
  }, [])
  // 定义表格列
  const columns = [
    {
      title: '客户名称',
      dataIndex: 'key',

      render: (key: string) => {
        return <div>{key}</div>
      }
    },
    {
      title: '客户状态',
      dataIndex: 'name',
      render: (name: string) => {
        return <div style={{ color: '#1777FF' }}>{name}</div>
      }
    },
    {
      title: '客户星级',
      dataIndex: 'kehu',
      sorter: {
        compare: (a: any, b: any) => a.kehu - b.kehu,
        multiple: 3,
      },
      render: (kehu: string) => {
        return <div style={{ color: '#1777FF' }}>{kehu}</div>
      }
    },
    {
      title: '首联系人',
      dataIndex: 'Collor',
      sorter: {
        compare: (a: any, b: any) => a.Collor - b.Collor,
        multiple: 3,
      },
      render: (kehu: string) => {
        return <div style={{ color: '#1777FF' }}>{kehu}</div>
      }
    },
    {
      title: '手机号码',
      dataIndex: 'price',
      sorter: {
        compare: (a: any, b: any) => a.price - b.price,
        multiple: 3,
      },
      render: (price: string | number) => {
        return <div>{price}</div>
      }
    },
    {
      title: '最后跟进',
      dataIndex: 'yprice',
      sorter: {
        compare: (a: any, b: any) => a.yprice - b.yprice,
        multiple: 3,
      },
      render: (yprice: string | number) => {
        return <div>{new Date(yprice).toLocaleString()}</div>
      }
    },
    {
      title: '未跟进天数 ',
      dataIndex: 'kprice',
      sorter: {
        compare: (a: any, b: any) => a.kprice - b.kprice,
        multiple: 3,
      },
      render: (kprice: string | number) => {
        return <div>{kprice}</div>
      }
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <a><WechatOutlined />跟进</a>
          <a onClick={() => {
            setName("编辑用户")
            setIsModalOpen(true)
            setList({ ...record })
          }}><SignatureOutlined />编辑</a>
          <a onClick={() => {
            // 置顶/取消置顶逻辑
            setPinnedIds(prev => {
              if (prev.includes(record.id)) {
                // 如果已经置顶，则取消置顶
                return prev.filter(id => id !== record.id);
              } else {
                // 否则添加置顶
                return [...prev, record.id];
              }
            });
          }}>
            <VerticalAlignTopOutlined />
            {pinnedIds.includes(record.id) ? '取消置顶' : '置顶'}
          </a>
          <Popconfirm
            title="删除弹窗"
            description="你是否要进行删除?"
            onConfirm={()=>{
              confirm(record.id)
            }}
            onCancel={cancel}
            okText="确定"
            cancelText="取消"
          >
            <a><DeleteOutlined />删除</a>
          </Popconfirm>

        </Space>
      ),
    },
  ];
  // 处理下拉框选择事件
  // 定义一个handleChange函数，用于处理值的变化
  const handleChange = (value: any) => {
    // 打印出选中的值
    console.log(`selected ${value}`);
  };
  // 处理日期选择事件
  // 定义一个onChange1函数，接收两个参数date和dateString
  const onChange1 = (date: string, dateString: any) => {
    // 打印date和dateString
    console.log(date, dateString);
  };
  // 定义下拉框选项
  const items = [
    {
      key: '1',
      label: '全部客户',

    },
    {
      key: '2',
      label: '我的客户',

    },
    {
      key: '3',
      label: '下属客户',

    },
    {
      key: '4',
      label: '重点客户',

    },
    {
      key: '5',
      label: '我协作的',

    },
    {
      key: '6',
      label: '下述协作的',

    },
  ];
  // 处理下拉框选择事件
  const onChange = (key: any) => {
    console.log(key);
  };


  const confirm: PopconfirmProps['onConfirm'] = (e) => {
    deleteLyh(e).then((res) => {
      mm()
    })
    message.success('删除成功');
  };

  const cancel: PopconfirmProps['onCancel'] = (e) => {
    console.log(e);
    message.error('取消删除');
  };

  // 定义表格数据

  return (
    <div>
      <div style={{ margin: '0 0 20px 0' }}>
        <Tabs defaultActiveKey="1" items={items} onChange={onChange} />
        <Space>
          <Input placeholder="搜索关键字" style={{ width: '200px' }} />
          <Select
            style={{ width: '200px' }}
            defaultValue="客户状态"
            onChange={handleChange}
            options={[
              { value: '客户状态', label: '客户状态' }
            ]}
          />
          <Select
            defaultValue="客户类型"
            style={{ width: '200px' }}
            onChange={handleChange}
            options={[
              { value: '客户类型', label: '客户类型' }
            ]}
          />
          <Select
            defaultValue="客户星级"
            style={{ width: '200px' }}
            onChange={handleChange}
            options={[
              { value: '客户星级', label: '客户星级' }
            ]}
          />
          <DatePicker onChange={onChange1} placeholder='最后跟进' />
          <Button type="primary"><SearchOutlined />查询</Button>
          <Button color="default" variant="dashed"><UndoOutlined />重置 </Button>
          <div style={{ color: 'blue' }}><FunnelPlotOutlined />高级搜索</div>
        </Space>
      </div>

      <Space>
        <Button color="primary" variant="solid" onClick={() => {
          setName("添加客户")
          setIsModalOpen(true)
        }}><PlusOutlined />添加</Button>
        <Button color="default" variant="outlined"><VerticalAlignBottomOutlined />导入</Button>
        <Button color="default" variant="outlined"><VerticalAlignTopOutlined />导出</Button>
        <Button color="default" variant="outlined"><RetweetOutlined />转移客户</Button>
        <Button color="default" variant="outlined"><ImportOutlined />添加协作</Button>
      </Space>
      <Table rowKey='id' columns={columns} dataSource={sortedData} pagination={{ defaultPageSize: 8 }} onChange={handleTableChange} />
      <Modal footer title={name} open={isModalOpen} onOk={handleOk} onCancel={handleCancel}  >
        <Myform key={new Date().getTime()} handleOk={handleOk} mm={mm} name={name} list={list} />
      </Modal>

    </div>
  )
}
